package com.whut.mobilesafe.service;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.ContentObserver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Handler;
import android.os.IBinder;
import android.os.SystemClock;
import android.provider.CallLog;
import android.telephony.PhoneStateListener;
import android.telephony.SmsManager;
import android.telephony.SmsMessage;
import android.telephony.TelephonyManager;
import android.util.Log;

import com.android.internal.telephony.ITelephony;
import com.whut.mobilesafe.db.dao.BlackListDao;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.logging.Filter;

/**
 * 作    者:yubo.xiaoyubo
 * 时    间：2015/12/26 9:53
 * 版    本：1.0
 * 描    述：黑名单服务，监听来电，遇到黑名单号码直接endCall()
 */
public class BlackListService extends Service {

    private MyPhoneStateListener mPhoneStateListener;
    private BlackListDao mDao;
    private TelephonyManager MTm;
    private MyContentResolve mContentResolve;
    private InnerBroadCastReceiver mInnerBroadCastReceiver;


    private static final int MODE_PHONE = 1;
    private static final int MODE_MESSAGE = 2;
    private static final int MODE_ALL = 3;

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {


        mDao = BlackListDao.getInstance(this);

        mPhoneStateListener = new MyPhoneStateListener();
        MTm = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
        MTm.listen(mPhoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);

        //拦截短信
        mInnerBroadCastReceiver = new InnerBroadCastReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction("android.provider.Telephony.SMS_RECEIVED");
        filter.setPriority(Integer.MAX_VALUE);
        registerReceiver(mInnerBroadCastReceiver, filter);
    }


    class MyPhoneStateListener extends PhoneStateListener {
        @Override
        public void onCallStateChanged(int state, String incomingNumber) {
            super.onCallStateChanged(state, incomingNumber);
            //如果当前状态是响铃状态
            if (state == TelephonyManager.CALL_STATE_RINGING) {
                int mode = mDao.getModeByNumber(incomingNumber);
                if (mode == MODE_PHONE || mode == MODE_ALL) {
                    endCall();
                    deletCallLog(incomingNumber);

                    mContentResolve = new MyContentResolve(new Handler(), incomingNumber);
                    getContentResolver().registerContentObserver(CallLog.Calls.CONTENT_URI, true, mContentResolve);
                }
            }
        }
    }


    //注册内容观察者 ，用户观察数据库的变化
    class MyContentResolve extends ContentObserver {

        private String incomingNumber;

        public MyContentResolve(Handler handler, String incomingNumber) {
            super(handler);
            this.incomingNumber = incomingNumber;
        }

        @Override
        public void onChange(boolean selfChange) {
            System.out.println("通话记录发生变化!!!");
            deletCallLog(incomingNumber);

            // 注销内容观察者
            getContentResolver().unregisterContentObserver(mContentResolve);
        }

    }

    /**
     * 删除通话记录
     *
     * @param incomingNumber 来电号码
     */
    private void deletCallLog(String incomingNumber) {
        getContentResolver().delete(CallLog.Calls.CONTENT_URI, " number = ?", new String[]{incomingNumber});
        Log.d("BlackListService", "删除电话");
    }

    //挂断电话
    private void endCall() {
        //获取android.os.ServiceManager类的对象的getService()方法
        try {
            Log.d("BlackListService", "挂断电话");

            Method method = Class.forName("android.os.ServiceManager").
                    getMethod("getService", String.class);
            // 获取远程TELEPHONY_SERVICE的IBinder对象的代理
            IBinder binder = (IBinder) method.invoke(null, new Object[]{TELEPHONY_SERVICE});
            // 将IBinder对象的代理转换为ITelephony对象
            ITelephony telephony = ITelephony.Stub.asInterface(binder);
            telephony.endCall();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onDestroy() {
        //取消注册监听短信
        if (mInnerBroadCastReceiver != null) {
            unregisterReceiver(mInnerBroadCastReceiver);
            mInnerBroadCastReceiver = null;
        }

        //取消监听
        MTm.listen(mPhoneStateListener, PhoneStateListener.LISTEN_NONE);
        mPhoneStateListener = null;
    }


    public class InnerBroadCastReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            Object[] objects = (Object[]) intent.getExtras().get("pdus");
            Log.d("InnerBroadCastReceiver", "-----for 循环没有进去！！！-------");
            for (Object obj : objects) {
                SmsMessage smsMessage = SmsMessage.createFromPdu((byte[]) obj);
                String originatingAddress = smsMessage.getOriginatingAddress();
                Log.d("InnerBroadCastReceiver","================="+originatingAddress);

                int mode = mDao.getModeByNumber(originatingAddress);
                Log.d("InnerBroadCastReceiver", "----------++++++---------");
                if (mode == MODE_MESSAGE || mode == MODE_ALL) {
                    Log.d("InnerBroadCastReceiver", "mode:" + mode);
                    abortBroadcast();
                }
            }
        }
    }
}
